package cn.gson.crm.controller.beforesale;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.OpportunityDao;
import cn.gson.crm.model.dao.SolutionDao;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.SalesOpportunity;
import cn.gson.crm.model.entity.Solution;

/**
 * 解决方案
 * @author PD
 *
 */
@Controller
@RequestMapping("solution")
public class SolutionController {

	@Autowired
	SolutionDao sodao;
	

	@Autowired
	OpportunityDao opdao;
	
	@Autowired
	EmployeeDao eDao;
	
	@RequestMapping
	public String solution() {
		return "beforesale/solution";
	}

		// 加载解决方案中的表格
		@RequestMapping("solutionform")
		@ResponseBody
		public Map<String,Object> form(@RequestParam(defaultValue = "1") int page,
				@RequestParam(defaultValue="20") int rows,HttpSession session){
			Map<String,Object> data = new HashMap<>();
			PageRequest pr = new PageRequest(page-1, rows,new Sort(Direction.ASC,"id"));
			Employee emp = (Employee) session.getAttribute("employee");
			if(emp!=null){
				//如果是销售员
				if(emp.getRole().getRoleName().equals("销售员")){
					Page<Solution> so1 = sodao.findByEmployeeAndIsDelete(emp, false, pr);
					data.put("rows", so1.getContent());
					data.put("total", so1.getTotalElements());
				}else{
					//管理人员
					Page<Solution> so = sodao.findAllByIsDelete(false, pr);
					data.put("rows", so.getContent());
					data.put("total", so.getTotalElements());
				}
			}
			return data;
			
		}
	
		//编辑与新增
		@RequestMapping({"solutioneditform","solutioneditform/{id}"})
		public String edit(@PathVariable(required = false) Long id, Model model) {
			if(id!=null){
			model.addAttribute("r",sodao.findOne(id));
			}
			return "beforesale/solution/solutionform";
		}
		

		/**
		 * 保存
		 * @author PD
		 * @param br
		 * @return
		 */
		@GetMapping("savenew")
		@ResponseBody
		@Transactional
		public JSONObject savenew(
				@RequestParam(value = "topic", required = false) String topic,
				@RequestParam(value = "content", required = false) String content,
				@RequestParam(value = "note", required = false) String note,
				@RequestParam(value = "time", required = false) String time,
				@RequestParam(value = "salesOppid", required = false) Long salesOppid,HttpSession session){
				JSONObject result = new JSONObject();
				Solution solution = new Solution();
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				Date date = null;
				try{
					date = formatter.parse(time);
				}catch(ParseException e){
						System.out.println("日期转换异常！");
					}
					solution.setContent(content);
					Employee emp =(Employee) session.getAttribute("employee");
					solution.setEmployee(emp);
					solution.setNote(note);
					solution.setSalesOpp(opdao.findOne(salesOppid));
					solution.setTime(date);
					solution.setTopic(topic);
					if(sodao.save(solution)!=null){
						result.put("message", "保存成功！");
					}else{
						result.put("message", "保存失败！");
					}
			return result;
		}
			
		@GetMapping("saveedit")
		@ResponseBody
		@Transactional
		public JSONObject saveedit(@RequestParam(value = "id", required = false) Long id,
				@RequestParam(value = "topic", required = false) String topic,
				@RequestParam(value = "content", required = false) String content,
				@RequestParam(value = "note", required = false) String note,
				@RequestParam(value = "time", required = false) String time,
				@RequestParam(value = "salesOppid", required = false) Long salesOppid,HttpSession session){
			JSONObject result = new JSONObject();
			System.out.println(time);
			Solution solution = sodao.findOne(id);
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				Date date = null;
				try{
					date = formatter.parse(time);
				}catch(ParseException e){
						System.out.println("日期转换异常！");
					}
					solution.setContent(content);
					Employee emp =(Employee) session.getAttribute("employee");
					solution.setEmployee(emp);
					solution.setNote(note);
					SalesOpportunity opp = opdao.findOne(salesOppid);
					solution.setSalesOpp(opp);
					solution.setTime(date);
					solution.setTopic(topic);
					if(sodao.save(solution)!=null){
						result.put("message", "保存成功！");
					}else{
						result.put("message", "保存失败！");
					}
		
			return result;
		}
		
		
		/**
		 * @author PD
		 * 批量删除
		 */
		@PostMapping("delete/{id}")
		@Transactional
		@ResponseBody
		public JSONObject delete(@PathVariable Long[] id) {
			JSONObject result = new JSONObject();
			try {
				//遍历id数组，先查询所有需要进行操作的对象
				for(int i=0;i<id.length;i++){
					Solution sos = sodao.findOne(id[i]);
					sos.setDelete(true);
					sodao.save(sos);
				}
				result.put("success", true);
			} catch (Exception e) {
				result.put("errorMsg", e.getStackTrace());
			}
			return result;
		}

		@RequestMapping("solutiondetaisform/{id}")
		public String solutiondetailsform(@PathVariable(required = false) Long id, Model model) {
			model.addAttribute("r",sodao.findOne(id));
		return "beforesale/solution/solutiondetaisform";
	}
		
		
		
		
}
